package com.example.boot.config.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.filter.CharacterEncodingFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder createPwdEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 拦截规则设置
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                // 不拦截静态资源
                .antMatchers("/static/**", "resources/**").permitAll()
                //不拦截登录页面
                .antMatchers("/login").permitAll()
                // 拦截其它一切请求
                .antMatchers("/index").hasAuthority("test1")
                .antMatchers("/add").hasAnyAuthority("test4")
                .antMatchers("/**").fullyAuthenticated()
                .and()
                // 采用表单的方式提交
                .formLogin()
//                // 设置自定义的登录页面
//                .loginPage("/login")
//                // 登录成功跳转到的页面
//                .successForwardUrl("/index")
//                // 登录失败跳转到的页面
//                .failureForwardUrl("/login?error=true")
                .and()
                .csrf().disable()
        ;

        //session管理,失效后跳转
        //http.sessionManagement().invalidSessionUrl("/login");
        //单用户1登录，如果有一个登录了，同一个用户在其他地方登录将前一个剔除下线
        //http.sessionManagement().maximumSessions(1).expiredSessionStrategy(expiredSessionStrategy());
//        //单用户登录，如果有一个登录了，同一个用户在其他地方不能登录
//        http.sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true);
//        //退出时清空cookies
//        http.logout().deleteCookies("JESSIONID");
//        // 禁用缓存
//        http.headers().cacheControl();
//        //解决中文乱码问题
//        CharacterEncodingFilter filter = new CharacterEncodingFilter();
//        filter.setEncoding("UTF-8"); filter.setForceEncoding(true);
//        http.addFilterBefore(filter, CsrfFilter.class);
        http.logout().logoutSuccessUrl("/index");
    }

}
